﻿using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Lottery.DBUtility;
using Lottery.Entity;
using System.Data;

namespace Lottery.DataAccess
{
    public class LotteryMatchTypeController
    {
        const string INSERT = "INSERT INTO LotteryMatchType(MatchTypeName) VALUES(" + PARM_MATCHTYPENAME + ")";
        const string SELECT_ALLMATCHTYPE = "SELECT * FROM LotteryMatchType";
        const string CONDITION_BYMATCHNAME = " WHERE MatchTypeName=" + PARM_MATCHTYPENAME;
        const string PARM_MATCHTYPENAME = "@MatchTypeName";
        const string CONDITION_UNDELETED = " WHERE IsDeleted = 0";

        public List<LotteryMatchType> GetAllUndeletedMatchType()
        {
            return LotterySQLEntityHelper<LotteryMatchType>.GetEntitySet(SELECT_ALLMATCHTYPE + CONDITION_UNDELETED);
        }

        public LotteryMatchType GetMatchTypeByName(string matchName)
        {
            return LotterySQLEntityHelper<LotteryMatchType>.GetEntity(SELECT_ALLMATCHTYPE + CONDITION_BYMATCHNAME,
                   new SqlParameter(PARM_MATCHTYPENAME, matchName));
        }

        public int Insert(string matchName)
        {
            int result = 0;
            if (GetMatchTypeByName(matchName) == null)
            {
                result = LotterySQLHelper.ExecuteNonQuery(CommandType.Text, INSERT, new SqlParameter(PARM_MATCHTYPENAME, matchName));
            }
            return result;
        }

        public int Insert(List<LotteryMatchType> lotteryMatchTypeSet)
        {
            int result = 0;

            IEnumerable<string> matchTypeNameSet = lotteryMatchTypeSet.Select(l => l.MatchTypeName).Distinct();

            List<LotteryMatchType> lotteryMatchTypeNameInDB = GetAllUndeletedMatchType();

            IEnumerable<string> matchTypeNameSetInDB = lotteryMatchTypeNameInDB.Select(l => l.MatchTypeName);

            foreach (string matchTypeName in matchTypeNameSet)
            {
                if (!lotteryMatchTypeNameInDB.Select(l => l.MatchTypeName == matchTypeName).Any())
                {
                    result += LotterySQLHelper.ExecuteNonQuery(CommandType.Text, INSERT, new SqlParameter(PARM_MATCHTYPENAME, matchTypeName));
                }
            }

            return result;
        }
    }
}
